<template>
  <div class="tagView">
    <el-scrollbar>
      <div class="scrollbar-flex-content">
        <el-tag
          v-for="(item, index) in $store.getters.tagsViewList"
          :key="item.fullPath"
          :closable="activePath == item.path ? false : true"
          :type="activePath == item.path ? 'primary' : 'info'"
          class="scrollbar-demo-item"
          @click="storeActive(item.path, index)"
          @close="closeTag(index)"
          @contextmenu.prevent="openMenu($event, index)"
        >
          {{ item.title }}
        </el-tag>
      </div>
    </el-scrollbar>
    <context-menu
      v-show="visible"
      :style="menuStyle"
      :closeCurrentIndex="selectIndex"
    ></context-menu>
  </div>
</template>

<script setup>
import { useRoute, useRouter } from 'vue-router'
import { useStore } from 'vuex'

import ContextMenu from './ContextMenu.vue'
import { ref, reactive, watch } from 'vue'

/**
 * 点击切换路由
 */
const route = useRoute()
const router = useRouter()
const activePath = ref(0)
// const storeActive = (path, index) => {
//   // profile
//   console.log('path', path)
//   // 1
//   console.log('index', index)
//   // {path:'/profile'}
//   console.log('route', route)
//   // userInfo
//   console.log('route.path', route.path)
//   router.push(path)
//   // userInfo
//   console.log('route.path111', route.path)
//   if (route.path === path) {
//     activeIndex.value = index
//   }
// }

const storeActive = (path, index) => {
  router.push(path)
  router.afterEach((to) => {
    if (to.path === path) {
      activePath.value = path
    }
    console.log('route.path', route.path)
    console.log('path', path)
  })
}
const store = useStore()
watch(
  route,
  (to, from) => {
    store.getters.tagsViewList.forEach((item, index) => {
      if (item.path === to.path) {
        activePath.value = item.path
      }
    })
  },
  {
    immediate: true
  }
)
/**
 * 关闭标签
 */
const closeTag = (index) => {
  store.commit('app/deleteOneTag', index)
}

// contextMenu 相关
const selectIndex = ref(0)
const visible = ref(false)
const menuStyle = reactive({
  left: 0,
  top: 0
})
/**
 * 展示 menu
 */
const openMenu = (e, index) => {
  const { x, y } = e
  menuStyle.left = x + 'px'
  menuStyle.top = y + 'px'
  selectIndex.value = index
  visible.value = true
}
const initMenuData = () => {
  selectIndex.value = 0
  visible.value = false
  menuStyle.value = {
    left: 0,
    top: 0
  }
}
// 点击body关闭右键菜单
watch(visible, (value) => {
  if (value) {
    document.body.addEventListener('click', initMenuData)
  } else {
    document.body.removeEventListener('click', initMenuData)
  }
})
</script>

<style lang="scss" scoped>
.tagView {
  height: 45px;
  .scrollbar-flex-content {
    display: flex;
    margin: 10px 0;
  }
  .scrollbar-demo-item {
    margin-left: 15px;
  }
}
</style>
